package org.irri.smta.util;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.irri.smta.domain.User;
import org.primefaces.context.RequestContext;

public class BeanUtils implements Serializable {

	private static final long serialVersionUID = 1L;
	
	public String getContextPath() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (facesContext != null) {
			HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
			if (session != null) {
				String contextPath = session.getServletContext().getContextPath();
				return contextPath;
			}
		}
		return null;
	}
	
	public Boolean setSessionUser(User user) {
		if (user != null && user.getId() != null) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			if (facesContext != null) {
				HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
				if (session != null) {
					session.setAttribute("user", user);
					if (session.getAttribute("user") != null) {
						return true;
					}
				}
			}
		}
		return false;
	}
	
	public User getSessionUser() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (facesContext != null) {
			HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
			if (session != null) {
				return (User) session.getAttribute("user");
			}
		}
		return null;
	}
	
	public void clearSessionUser() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (facesContext != null) {
			HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
			if (session != null) {
				session.removeAttribute("user");
			}
		}
	}
	
	public Boolean validateUser() {
		return (getSessionUser() != null);
	}
	
	public void navigateToView(String viewName) {
		if (viewName != null && viewName.trim().length() > 0) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			if (facesContext != null) {
				facesContext.getApplication().getNavigationHandler()
						.handleNavigation(facesContext, null, viewName);
			}
		}
	}

	public void navigateToPopupView(String viewName) {
		if (viewName != null && viewName.trim().length() > 0) {
			RequestContext requestContext = RequestContext.getCurrentInstance();
			if (requestContext != null) {
				requestContext.execute("window.open('" + viewName + "', '_newtab')");
			}
		}
	}

	public void updateInfoMessage(String summary, String message) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_INFO, summary, message));
	}

}
